<template>
	<!-- 新建地图页面 -->
	<view style="background-color:#F5F6F7;">
		<!-- 顶部搜索 -->
		<view class="headerStyle">
			<view class="iconStyle" @click="goback()">
				<u-icon name="arrow-left"></u-icon>
			</view>
			<view class="searchStyle" @click="moreAdderss">
				<u-search bgColor="#FFF" :showAction="false" :disabled="true" placeholder="搜索门店名称"></u-search>
			</view>
		</view>
		<!-- 地图 -->
		<view class="page-section page-section-gap">
			<map style="width: 100%; height: 300px;" :latitude="latitude" :longitude="longitude" :markers="covers"
				 @markertap="handleMarkerTap"  @callouttap="handleCalloutTap">
			</map>
		</view>
		<!-- 定位 -->
		<view class="current-md-address">
			<view class="again-action">
				<view class="" style="width: 500rpx;">
					<view class="">
						<u-icon name="map-fill" color="#262626" size="34"></u-icon>
						<text class="text1" style="margin-left: 10rpx;">
							{{newAddress}}
						</text>
					</view>
					<view class="text2">
						{{address}}
					</view>
				</view>
				<view class="" @click="location" style="display: flex; color: #0784EB; align-items: center;">
					<i class="iconfont icon-exchangerate"></i>
					<text style="margin-left: 10rpx;">{{ $t("mdAdmin.location") }}</text>
				</view>

			</view>
		</view>

		<!-- 附近门店 -->

		<view class="list-section">
			<view style="font-weight: 600;">附近门店</view>
			<view :class="[isOpen(item) ? '' : 'shop-close', 'md-item']" v-for="(item, index) in mdList" :key="index"
				@click="selectMdToStorage(item,index)">
				<view class="md-img">
					<image :src="item.cover_url" mode="aspectFill"> </image>
					<view class="shop-status" v-if="!isOpen(item)">{{
		      isOpen(item) ? "营业中" : "已打烊"
		    }}</view>
				</view>
				<view class="" style="width: 100%; display: flex; justify-content: space-between; align-items: center;">
					<view class="md-info">
						<view class="info-box">
							<view class="md-name">{{ item.name }}</view>
							<view class="md-address">
								<text class="detail">{{
					  item.province_name +
					  " " +
					  item.city_name +
					  " " +
					  item.district_name +
					  " " +
					  item.address
					}}</text>
							</view>
							<view class="shop-time" v-if="item.start_time">
								<text>{{ $t("shop.startTime") }}：</text>
								<text>{{
					  item.shop_time_type == 0
					    ? "全天"
					    : item.start_time + "~" + item.end_time
					}}</text>
							</view>
							<view class="shop-detail">
								<text class="distance">{{ $t("shop.distance") }}{{ item.distance }}</text>
							</view>
						</view>
					</view>
					<view class="shopsss " :class="{ 'shop-icons': selectedItem === index }">
						<u-icon name="checkbox-mark" color="#FFF" size="20"></u-icon>
					</view>
				</view>
			</view>
		</view>
		<view class="btnStyle">
			<u-button shape="circle" type="error" @click="sure" text="">确定门店</u-button>
		</view>
	</view>
</template>

<script>
	import goodsCart from "@/api/goodscart.js";
	export default {
		data() {
			return {
				selectedItem: 0,
				address: '',
				newAddress: '',
				title: 'map',
				latitude: null,
				longitude: null,
				id: 111, // 使用 marker点击事件 需要填写id
				covers: [],

				mdData: {},
				searchVal: "",
				page: 1,
				pageSize: 20,
				row_count: 0,
				mdList: [],
				backUrl: "",
				storeMd: {},
				loadText: {
					loadmore: "轻轻上拉",
					loading: "努力加载中",
					nomore: "没有更多了~"
				},
				status: "nomore",
				item: {},
			}
		},
		onLoad() {
			setTimeout(() => {
				this.initData();
			}, 0);
		},
		onReachBottom() {
			if (this.page * this.pageSize >= this.row_count) return;
			this.page++;
			let params = {
				loadMore: true,
				page: this.page
			};
			if (this.searchVal) {
				params["keyword"] = this.searchVal;
			}
			if (this.longitude) {
				params["longitude"] = this.longitude;
			}
			if (this.latitude) {
				params["latitude"] = this.latitude;
			}
			this.getMdList(params);
		},
		methods: {
			    handleMarkerTap(e) {
			      const markerId = e.detail.markerId;
			      this.covers.forEach(marker => {
			        if (marker.id === markerId) {
			          marker.callout.display = 'ALWAYS'; // 设置为ALWAYS以始终显示callout
					  
					  let item = this.covers.find(el=>el.id === markerId);
					  for (let i = 0; i < this.mdList.length; i++) {
					       if(this.mdList[i].id==item.id){
							     item.iconPath = this.mdList[i].cover_url
						   }
					  }
			        } else {
			          marker.callout.display = 'BYCLICK'; // 设置其他标记的callout显示方式为BYCLICK
					    // 初始化一个空数组
					    let itemsArray = [];
					    
					    // 查找符合条件的元素，并将其添加到数组中
					    this.covers.forEach((el) => {
					      if (el.id !== markerId) {
					       el.iconPath = "/static/css/sss.png"
					      }
					    });   
			        }
			      });
			    },
			    handleCalloutTap(e) {
			      // e 参数包含有关触发事件的详细信息
			      // 在这里执行点击callout后的操作
			    },
			// 点击返回
			goback() {
				uni.navigateBack()
			},
			// 点击确认门店逻辑
			sure() {
				try {
					if (!this.isOpen(this.item)) {
						uni.showToast({
							title: "该店铺已打样！",
							duration: 2000,
							icon: "none"
						});
						return;
					}

					uni.setStorageSync("storeMdData", JSON.stringify(this.item));
					uni.setStorageSync("MdDataReload", "true");
					goodsCart.getCartList();
					let mdBackUrl = uni.getStorageSync("mdBackUrl");
					if (mdBackUrl) {
						uni.reLaunch({
							url: mdBackUrl
						});
						return;
					}

					if (!this.backUrl) {
						uni.switchTab({
							url: "/pages/home/home"
						});
					} else {
						let {
							backUrl
						} = this;

						if (backUrl === "/alipay-order/orderMeal/orderMeal") {
							backUrl += `?md_id=${this.item.id}`;
						}

						uni.reLaunch({
							url: backUrl
						});
					}
				} catch (error) {
					this.$utils.goBack();
				}
			},
			// 选中门店
			selectMdToStorage(item, index) {
				this.item = item
				this.selectedItem = index;
			},
			// 门店是否营业
			isOpen(item) {
				if (item.open_status == 0) return false;
				if (item.shop_time_type == 0) return true;
				if (!item.start_time) return true;
				let date = new Date();
				let hour = date.getHours();
				let minutes = date.getMinutes();
				let [startBefore, startAfter] = item.start_time.split(":");
				let [endBefore, endAfter] = item.end_time.split(":");
				if (hour >= startBefore && hour < endBefore) {
					return true;
				}
				return false;
			},

			// 获取门店列表
			getMdList(params) {
				uni.showLoading({
					title: this.$t("home.loading")
				});
				this.$allrequest.shop.getMdList(params).then((res) => {
					uni.hideLoading();
					if (!res.code) {
						if (res.data.list.length) {
							res.data.list.forEach((el) => {
								let [latitude, longitude] = el.coordinate.split(",");
								el.latitude = latitude;
								el.longitude = longitude;
							});
						}

						if (params.loadMore) {
							this.mdList = [...this.mdList, ...res.data.list];

						} else {
							this.mdList = res.data.list;
							// this.covers.push({
							// 	id:9999,
							// 	latitude: this.latitude,
							// 	longitude: this.longitude,
							// 	iconPath: '/static/css/ddd.png',
							// 	height: 40,
							// 	width: 40,
							// })
							for (let i = 0; i < this.mdList.length; i++) {
								this.covers.push({
									id: Number(this.mdList[i].id),
									latitude: this.mdList[i].latitude,
									longitude: this.mdList[i].longitude,
									iconPath: '/static/css/sss.png',
									height: 40,
									width: 40,
									callout: {
										content: this.mdList[i].name,
										// content:``,
										color: '#000106',
										fontSize: '10',
										borderRadius: '10',
										bgColor: '#fff',
										padding: '5',
										display: 'BYCLICK', // 设置为BYCLICK以便根据点击显示
										anchorY:5,
									},
								});

							}
						}
						if (params.readAddress && res.data.list.length) {
							this.address =
								res.data.list[0].province_name +
								res.data.list[0].city_name +
								res.data.list[0].district_name +
								res.data.list[0].address;
						}
						if (!params.readAddress && !res.data.list.length) {
							let mdLocalData = uni.getStorageSync("storeMdData");
							if (mdLocalData) {
								let mdData = JSON.parse(mdLocalData);
								this.address = mdData.address;
							}
						}
						this.row_count = res.data.row_count;

						if (this.mdList.length >= parseInt(this.row_count)) {
							this.status = "nomore";
						}
					}
				});
			},
			// 获取定位
			async initData() {
				const res = await this.$store.dispatch("getLocation");
				if (res) {
					let {
						longitude,
						latitude
					} = res;
					this.longitude = longitude;
					this.latitude = latitude;
				}
				this.getLocationInfo();
				this.getMdList({
					page: this.page,
					longitude: this.longitude,
					latitude: this.latitude
				});
			},
			// 修改定位
			getLocationInfo() {
				this.$allrequest.diyNew
					.getLocationInfo({
						longitude: this.longitude,
						latitude: this.latitude
					})
					.then((res) => {
						this.newAddress =	res.data.district +
								res.data.street;
						if (!res.code) {
							this.address =
								res.data.province +
								res.data.city +
								res.data.district +
								res.data.street;
						}


					});
			},
			// 切换定位
			async location() {
				const apiRes = await this.$store.dispatch("getLocation");
				if (apiRes.longitude) {
					uni.chooseLocation({
						success: (res) => {
							if (res.errMsg == "chooseLocation:ok") {
								this.longitude = res.longitude;
								this.latitude = res.latitude;
								this.address = res.address;
								this.newAddress = res.name
								this.page = 1;
								this.getMdList({
									page: this.page,
									longitude: this.longitude,
									latitude: this.latitude
								});
							}
						},
						fail: (err) => {
							if (err && (err.errno === 112 || err.errno === 104)) {
								uni.showToast({
									title: "未同意隐私协议，该功能不可使用！",
									duration: 2000,
									icon: "none"
								});
							}
						}
					});
				}
			},
			moreAdderss() {
				uni.navigateTo({
					url: `/shop/newAdderss/newAdderss?longitude=${this.longitude}&latitude=${this.latitude}`
				})
			}


		}
	}
</script>

<style lang="scss" scoped>
	.shopsss {
		width: 30rpx;
		height: 30rpx;
		border-radius: 50%;
		border: 1px solid black;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.shop-icons {
		width: 30rpx;
		height: 30rpx;
		border-radius: 50%;
		background-color: #f0250e;
		display: flex;
		justify-content: center;
		align-items: center;
		border: none;
	}

	.btnStyle {
		width: 100%;
		background-color: #FFF;
		padding: 20rpx 30rpx 40rpx 30rpx;
		position: fixed;
		bottom: 0;


	}

	.headerStyle {
		display: flex;
		justify-content: center;
		align-items: center;
		position: absolute;
		top: 12px;
		left: 14rpx;
		z-index: 999;

	}

	.iconStyle {
		width: 64rpx;
		height: 64rpx;
		border-radius: 50%;
		background-color: #FFF;
		border: 1px solid #ccc;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-right: 10rpx;
	}

	.searchStyle {
		width: 600rpx;
		height: 64rpx;
	}

	.current-md-address {
		background-color: #F5F6F7;
		width: 100%;

		border-radius: 12rpx 12rpx 0rpx 0rpx;
	}

	.again-action {
		display: flex;
		justify-content: space-between;
		padding: 30rpx 24rpx;
		align-items: flex-start;
	}

	.text1 {
		font-weight: 600;
	}

	.text2 {
		color: #999999;
	}




	.md-page {
		position: relative;
		min-height: 100vh;
		background: #f2f2f2;

		.header-search {
			background: #fff;
			padding: 18rpx 24rpx;
		}

		.current-md {
			position: relative;
			padding: 0 24rpx;
			margin-bottom: 24rpx;
			background: #fff;
			border: 4rpx solid #f60413;
			border-radius: 20rpx;

			.active {
				position: absolute;
				right: -4rpx;
				top: -4rpx;
				width: 174rpx;
			}
		}

		.current-title {
			width: 100%;
			height: 90rpx;
			padding-left: 24rpx;
			display: flex;
			align-items: center;
			font-size: 30rpx;
			font-family: PingFang SC;
			font-weight: 600;
			color: rgba(29, 29, 29, 0.94);
			background: #f2f2f2;
		}

		.current-md-address {
			padding: 0 24rpx;
			// width: 100%;
			height: 76rpx;
			background: linear-gradient(180deg, #ffffff 0%, #f0f0f0 100%);
			display: flex;
			justify-content: space-between;
			align-items: center;

			.address {
				max-width: 486rpx;
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
				font-size: 30rpx;
				font-family: PingFang SC;
				font-weight: 400;
				color: rgba(29, 29, 29, 0.94);
			}

			.again-action {
				display: flex;
				justify-content: flex-end;
				align-items: center;

				.iconfont {
					color: #f0250e;
					font-size: 34rpx;
					margin-right: 1vw;
				}

				text {
					font-size: 28rpx;
					font-family: PingFang SC;
					font-weight: 400;
					color: #f0250e;
				}
			}
		}

	}

	.list-section {
		width: 700rpx;
		margin: 0 auto;
		border-radius: 20rpx;
		background-color: #FFF;
		padding: 20rpx 20rpx 120rpx 20rpx;

		// padding-bottom: 4.8vw;
		.md-item {
			width: 100%;
			display: flex;
			align-items: flex-start;
			padding: 24rpx 0;
			position: relative;

			&:after {
				content: "";
				position: absolute;
				left: 156rpx;
				bottom: 0;
				right: 0;
				height: 2rpx;

			}

			&:lasf-of-type:after {
				display: none;
			}

			.md-img {
				position: relative;
				width: 144rpx;
				height: 144rpx;
				border-radius: 10rpx;

				image {
					width: 144rpx;
					height: 144rpx;
					display: block;
				}
			}

			.shop-status {
				position: absolute;
				left: 0;
				bottom: 0;
				width: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 0px 0px 10rpx 10rpx;
				background: rgba(38, 38, 38, 0.5);
				font-size: 24rpx;
				color: #ffffff;
			}

			.md-info {
				flex: 1;
				margin-left: 18rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.info-box {
					flex: 1;

					.md-name {
						font-size: 26rpx;
						font-weight: 400;
						color: #262626;
						max-width: 432rpx;
						word-break: break-all;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						/* 这里是超出几行省略 */
						overflow: hidden;
					}

					.md-address {
						padding: 4rpx 0 10rpx;

						.detail {
							font-size: 24rpx;
							color: #8c8c8c;
							word-break: break-all;
							text-overflow: ellipsis;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
							/* 这里是超出几行省略 */
							overflow: hidden;
							color: #8c8c8c;
							line-height: 30rpx;
						}
					}

					.shop-time {
						font-size: 24rpx;
						color: #262626;
					}
				}

				.shop-detail {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.distance {
						font-size: 24rpx;
						color: #f0250e;
					}
				}
			}
		}

		.shop-close {
			.md-info {
				.info-box {
					.md-name {
						color: #bfbfbf;
					}

					.md-address {
						.detail {
							color: #bfbfbf;
						}
					}

					.shop-time {
						color: #bfbfbf;
					}

					.shop-status {
						background: #eeeeee;
						color: #8c8c8c;
					}
				}
			}
		}
	}

	.store-md {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;
		padding: 0 24rpx;
		height: 102rpx;
		background: #fff;
		border-radius: 20rpx;
		font-size: 30rpx;
		position: relative;

		.md-img {
			width: 50rpx;
			height: 50rpx;
			border-radius: 8rpx;
			background: #ffffff;
			overflow: hidden;
			border: 1px solid #f7f7f7;

			image {
				width: 100%;
				height: 100%;
				display: block;
			}
		}

		.md-info {
			flex: 1;
			margin-left: 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.info-box {
				flex: 1;

				.md-name {
					font-size: 28rpx;
					font-family: PingFang SC;
					font-weight: 400;
					color: #262626;
					max-width: 432rpx;
					word-break: break-all;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					/* 这里是超出几行省略 */
					overflow: hidden;
				}

				.md-address {
					margin-top: 4rpx;
					max-width: 432rpx;
					word-break: break-all;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					/* 这里是超出几行省略 */
					overflow: hidden;

					.detail {
						font-size: 24rpx;
						font-family: PingFang SC;
						font-weight: 400;
						color: #8c8c8c;
					}
				}

				.shop-time {
					font-size: 24rpx;
					font-family: PingFang SC;
					font-weight: 400;
					color: #8c8c8c;
					margin-top: 8rpx;
				}

				.shop-status {
					margin-top: 8rpx;
					width: 80rpx;
					height: 32rpx;
					background: #f0250e;
					border-radius: 4rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 20rpx;
					font-family: PingFang SC;
					font-weight: 400;
					color: #ffffff;
				}
			}

			.shop-detail {
				width: 196rpx;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.distance {
					font-size: 22rpx;
					font-family: PingFang SC;
					font-weight: 400;
					color: #8c8c8c;
					margin-bottom: 32rpx;
				}
			}
		}
	}


	.warning {
		color: #f0250e !important;
	}

	.icon-success-fill {
		margin: 0rpx 10rpx 0 0;
		font-size: 40rpx;
	}

	.store-md.on {
		color: #f0250e;
	}



	.current-md-address-let {
		display: flex;
		align-items: center;
		flex: 1;
		overflow: hidden;

		image {
			margin-right: 10rpx;
			width: 28rpx;
		}

		.address {
			flex: 1;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}
	}

	.md-page-box {
		padding: 0 24rpx 200rpx;
	}
</style>